"""
mysql连接器

"""
import os

from dotenv import load_dotenv
from flask_cors import CORS
from playhouse.pool import PooledMySQLDatabase
from playhouse.shortcuts import ReconnectMixin
from utils.config import get_config

cors = CORS()
db_config = {
    'host': get_config('DB_HOST'),
    'port': get_config('DB_PORT'),
    'user': get_config('DB_USER'),
    'password': get_config('DB_PASSWORD'),
    'database': get_config('DB_DATABASE'),
}


class ConnectMySQL(ReconnectMixin, PooledMySQLDatabase):
    _instance = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.sql_log = []

    @classmethod
    def get_db_instance(cls):
        if not cls._instance:
            cls._instance = cls(**db_config, max_connections=500, stale_timeout=300, timeout=5)
        return cls._instance

    def execute_sql(self, sql, params):
        self.sql_log.append({'sql': sql, 'params': params})
        return super().execute_sql(sql, params)


# 数据库实例
db = ConnectMySQL.get_db_instance()

# sdn_db_config = {
#     'host': os.getenv('SDN_DB_HOST'),
#     'port': int(os.getenv('SDN_DB_PORT')),
#     'user': os.getenv('SDN_DB_USER'),
#     'password': os.getenv('SDN_DB_PASSWORD'),
#     'database': os.getenv('SDN_DB_DATABASE'),
# }
#
#
# class SDNReconnectPooledMySQLDatabase(ReconnectMixin, PooledMySQLDatabase):
#     _instance = None
#
#     @classmethod
#     def get_db_instance(cls):
#         if not cls._instance:
#             cls._instance = cls(**sdn_db_config, max_connections=500, stale_timeout=300, timeout=5)
#         return cls._instance
#
#
# # 数据库实例
# sdn_db = SDNReconnectPooledMySQLDatabase.get_db_instance()
